/**
 * Created by L.jp
 * Description:输入一棵二叉搜索树，将该二叉搜索树转换成一个排序的循环双向链表。
 * 要求不能创建任何新的节点，只能调整树中节点指针的指向。
 * User: 86189
 * Date: 2022-12-13
 * Time: 22:52
 */
class Node {
    public int val;
    public Node left;
    public Node right;
    
    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }
    
    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
public class Solution {
    Node pre = null, head = null;
    public Node treeToDoublyList(Node root) {
        if (root == null) return root;
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    }
    void dfs(Node root){
        if (root == null) return; // 递归边界: 叶子结点返回
        dfs(root.left);
        if (pre != null) pre.right = root;
        else head = root; // 链表头结点
        root.left = pre;
        pre = root;
        dfs(root.right);
    }

}
